package com.zyh.demo;

import com.zyh.domain.Student;

import java.io.*;
import java.util.ArrayList;

/**
 * @Author zyh
 * @Date 2024/8/6 15:51
 * @Description 对象克隆
 */

public class IODemo6 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student stu1 = new Student("zyh", 20);
        Student newStu1 = cloneObject(stu1);
        System.out.println(newStu1);
        ArrayList<Student> list=new ArrayList<>();
        list.add(new Student("cxk",22));

    }
    public static <T> T cloneObject(T t) throws IOException, ClassNotFoundException {
        //存到内存数组中
        //创建一个内存数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //创建对象写入流
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        //开始写
        oos.writeObject(t);
        oos.flush();
        oos.close();
        //从内存数组中读取
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        T newObj = (T) ois.readObject();
        return newObj;
    }
}
